package com.probox.common.entity.service.product.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.List;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.enums.SpecsType;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.ProductException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.redis.service.RedisService;
import com.probox.common.entity.service.product.IProductPropertyValuesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.product.ProductSpecsMapper;
import com.probox.common.entity.domain.product.ProductSpecs;
import com.probox.common.entity.service.product.IProductSpecsService;

/**
 * 商品规格/属性Service业务层处理
 *
 *
 * @date 2021-05-27
 */
@Service
public class ProductSpecsServiceImpl extends ServiceImpl<ProductSpecsMapper, ProductSpecs> implements IProductSpecsService {
    @Autowired
    private ProductSpecsMapper productSpecsMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IProductPropertyValuesService iProductPropertyValuesService;

    /**
     * 查询商品规格/属性
     *
     * @param specsUid 商品规格/属性ID
     * @return 商品规格/属性
     */
    @Override
    public ProductSpecs selectProductSpecsById(Long specsUid) {
        return this.getById(specsUid);
    }

    /**
     * 查询商品规格/属性列表
     *
     * @param productSpecs 商品规格/属性
     * @return 商品规格/属性
     */
    @Override
    public List<ProductSpecs> queryList(ProductSpecs productSpecs) {
        QueryWrapper<ProductSpecs> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(productSpecs.getSpecsName())) && productSpecs.getSpecsName() != null) {
            queryWrapper.like("SPECS_NAME", productSpecs.getSpecsName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productSpecs.getDataStatus())) && productSpecs.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", productSpecs.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(productSpecs.getSpecsType())) && productSpecs.getSpecsType() != null) {
            queryWrapper.eq("SPECS_TYPE", productSpecs.getSpecsType());
        }
        Long platformId = SecurityUtils.getPlatformId();
        if (platformId != null) {
            queryWrapper.eq("PLATFORM_UID", platformId);
        } else {
            throw new BaseException("当前账号异常");
        }
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (StringUtils.isNotEmpty(String.valueOf(productSpecs.getDataPriority())) && productSpecs.getDataPriority() != null) {
            queryWrapper.orderByAsc("DATA_PRIORITY");
        } else {
            queryWrapper.orderByAsc("DATA_PRIORITY");
            queryWrapper.orderByDesc("UPDATE_TIME");
        }
        return productSpecsMapper.selectList(queryWrapper);
    }

    /**
     * 新增商品规格/属性
     *
     * @param productSpecs 商品规格/属性
     * @return 结果
     */
    @Override
    public boolean insertProductSpecs(ProductSpecs productSpecs) {
        // 名称不能重名
        Integer result = queryName(productSpecs.getSpecsName(), null);
        if (result > 0) {
            if (SpecsType.specs.getKey().equals(productSpecs.getSpecsType())) {
                throw new ProductException("商品规格名称不能重名！");
            } else {
                throw new ProductException("商品属性名称不能重名！");
            }
        }
        Long userId = SecurityUtils.getUserId();
        DateTime date = DateUtil.date();
        productSpecs.setPlatformUid(SecurityUtils.getPlatformId());
        productSpecs.setUpdateUid(userId);
        productSpecs.setUpdateTime(date);
        productSpecs.setUpdateName(SecurityUtils.getUsername());
        productSpecs.setDataStatus(DataStatus.valid.getKey());
        redisService.deleteObject(CachePrefix.PRODUCT_SPECS_SELECT+SecurityUtils.getPlatformId());
        redisService.deleteObject(CachePrefix.PRODUCT_PROPERTY_SELECT+SecurityUtils.getPlatformId());
        return this.save(productSpecs);

    }

    /**
     * 修改商品规格/属性
     *
     * @param productSpecs 商品规格/属性
     * @return 结果
     */
    @Override
    public boolean updateProductSpecs(ProductSpecs productSpecs) {
        // 名称不能重名
        Integer result = queryName(productSpecs.getSpecsName(), productSpecs.getSpecsUid());
        if (result > 0) {
            if (SpecsType.specs.getKey().equals(productSpecs.getSpecsType())) {
                throw new ProductException("商品规格名称不能重名！");
            } else {
                throw new ProductException("商品属性名称不能重名！");
            }
        }
        if(DataStatus.invalid.getKey().equals(productSpecs.getDataStatus())){
            if (SpecsType.specs.getKey().equals(productSpecs.getSpecsType())) {
                if(iProductPropertyValuesService.usePro(productSpecs.getSpecsUid()))
                    throw  new ProductException("该规格已被使用,无法无效！");
            }
        }
        productSpecs.setUpdateUid(SecurityUtils.getUserId());
        productSpecs.setUpdateName(SecurityUtils.getUsername());
        productSpecs.setUpdateTime(DateUtil.date());
        redisService.deleteObject(CachePrefix.PRODUCT_SPECS_SELECT+SecurityUtils.getPlatformId());
        redisService.deleteObject(CachePrefix.PRODUCT_PROPERTY_SELECT+SecurityUtils.getPlatformId());
        return this.updateById(productSpecs);
    }

    /**
     * 批量删除商品规格/属性
     *
     * @param specsUids 需要删除的商品规格/属性ID
     * @return 结果
     */
    @Override
    public boolean deleteProductSpecsByIds(Long[] specsUids) {
        UpdateWrapper<ProductSpecs> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("SPECS_UID", Arrays.asList(specsUids));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    /**
     * 防止重名
     *
     * @param name 名字
     * @param uid  类别ID
     * @return
     */
    public Integer queryName(String name, Long uid) {
        QueryWrapper<ProductSpecs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SPECS_NAME", name);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        if (uid != null) {
            queryWrapper.ne("SPECS_UID", uid);
        }
        Integer integer = productSpecsMapper.selectCount(queryWrapper);
        return integer;
    }

    /**
     * 获取查询属性后的数组
     *
     * @return
     */
    @Override
    public Long[] selectProductPropertyArray() {
        Long[] propertyUid = null;
        QueryWrapper<ProductSpecs> queryWrapper = Wrappers.query();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        queryWrapper.eq("SPECS_TYPE",SpecsType.property.getKey());
        queryWrapper.orderByAsc("DATA_PRIORITY");
        List<ProductSpecs> productSpecs = productSpecsMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(productSpecs)) {
            int size = productSpecs.size();
            propertyUid = new Long[size];
            Integer index = 0;
            for (ProductSpecs specs : productSpecs) {
                propertyUid[index] = specs.getSpecsUid();
                index++;
            }
        }
        return propertyUid;
    }

    /**
     *  获取规格的下拉框
     * @return
     */
    @Override
    public List<ProductSpecs> bulidSelect(){
        Long platformId = SecurityUtils.getPlatformId();
        if(platformId == null) throw new BaseException("当前账号异常");
        String key = CachePrefix.PRODUCT_SPECS_SELECT+platformId;
        List<ProductSpecs> list = redisService.getCacheList(key);
        if(ObjectUtil.isEmpty(list)){
            QueryWrapper<ProductSpecs> queryWrapper = Wrappers.query();
            queryWrapper.eq("PLATFORM_UID", platformId);
            queryWrapper.eq("SPECS_TYPE", SpecsType.specs.getKey());
            queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            queryWrapper.orderByAsc("DATA_PRIORITY");
            list = productSpecsMapper.selectList(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)) redisService.setCacheList(key, list);
        }
        return list;
    }
    /**
     *  获取规格的下拉框
     * @return
     */
    @Override
    public List<ProductSpecs> bulidSelect(String type){
        Long platformId = SecurityUtils.getPlatformId();
        if(platformId == null) throw new BaseException("当前账号异常");
        String key = CachePrefix.PRODUCT_PROPERTY_SELECT+platformId;
        List<ProductSpecs> list = redisService.getCacheList(key);
        if(ObjectUtil.isEmpty(list)){
            QueryWrapper<ProductSpecs> queryWrapper = Wrappers.query();
            queryWrapper.eq("PLATFORM_UID", platformId);
            queryWrapper.eq("SPECS_TYPE", type);
            queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
            queryWrapper.orderByAsc("DATA_PRIORITY");
            list = productSpecsMapper.selectList(queryWrapper);
            if(ObjectUtil.isNotEmpty(list)) redisService.setCacheList(key, list);
        }
        return list;
    }


}
